package com.sec.foodit;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Vibrator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

public class HomeScreenActivity extends Activity implements SensorEventListener{
	
	public ProgressDialog pd;
	
	private long lastTime;
    private float speed;
    private float lastX;
    private float lastY;
    private float lastZ;
   
    private float x, y, z;
    private static final int SHAKE_THRESHOLD = 1000;
   
	private static final int DATA_X = SensorManager.DATA_X;
    private static final int DATA_Y = SensorManager.DATA_Y;
    private static final int DATA_Z = SensorManager.DATA_Z;
   
    private SensorManager sensorManager;
    private Sensor accelerormeterSensor;
    
    private boolean isPressedShake = false;
	
	private ActivityManager am = ActivityManager.getInstance();
	private Vibrator vibe = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		vibe = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
		
		am.addActivity(this);
		
		final ActionBar actionBar = getActionBar();
 		actionBar.setDisplayOptions(ActionBar.DISPLAY_USE_LOGO);
 		actionBar.setIcon(R.drawable.act_logo);
 		
 		//센서 객체 초기화
 		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerormeterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
 		
		setContentView(R.layout.activity_home_screen);
		
		setEvent();
	}
	
	@Override
	public void onStart() {
		super.onStart();
		   
		if (accelerormeterSensor != null)
		    sensorManager.registerListener(this, accelerormeterSensor, SensorManager.SENSOR_DELAY_GAME);
	}
	
	@Override
	public void onStop() {
		super.onStop();
   
		if (sensorManager != null) 
			sensorManager.unregisterListener(this);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int menuId = item.getItemId();
		vibe.vibrate(50);
		 
		//이벤트 할당
		switch(menuId) {
			case R.id.menu_nearby:
				startActivity(new Intent("com.sec.foodit.HomeScreenActivity").setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				break;
			case R.id.menu_myboard:
				startActivity(new Intent("com.sec.foodit.MyBoardActivity").setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				break;
			case R.id.menu_favorite:
				startActivity(new Intent("com.sec.foodit.FavoriteActivity").setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				break;
			case R.id.menu_settings:
				startActivity(new Intent("com.sec.foodit.SettingsActivity").setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				break;
		}
		overridePendingTransition(0, 0);
		finish();
		return true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater(); 
		menuInflater.inflate(R.menu.activity_tabs, menu); 
		return true; 
	}
	
	public void setEvent() {
		ImageButton pBtn1 = (ImageButton)findViewById(R.id.pBtn1);
		ImageButton pBtn2 = (ImageButton)findViewById(R.id.pBtn2);
		ImageButton pBtn3 = (ImageButton)findViewById(R.id.pBtn3);
		ImageButton pBtn4 = (ImageButton)findViewById(R.id.pBtn4);
		ImageButton pBtn5 = (ImageButton)findViewById(R.id.pBtn5);
		ImageButton pBtn6 = (ImageButton)findViewById(R.id.pBtn6);
		ImageButton pBtn7 = (ImageButton)findViewById(R.id.pBtn7);
		ImageButton pBtn8 = (ImageButton)findViewById(R.id.pBtn8);
		
		ImageButton btnShake = (ImageButton)findViewById(R.id.btnShake);
		
		btnShake.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction() == MotionEvent.ACTION_UP) {
					isPressedShake = false;
				} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
					isPressedShake = true;
				}
				return false;
			}
		});
		
		pBtn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn5.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn6.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn7.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
		
		pBtn8.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.sec.foodit.RestActivity"));
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			AlertDialog dialog = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Foodit을 종료하시겠습니까?");
			//builder.setMessage("Foodit을 종료하시겠습니까?");
			builder.setPositiveButton("종료", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					am.finishAllActivity();
				}
			});
			builder.setNegativeButton("취소", null);
			builder.show();
			
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            long currentTime = System.currentTimeMillis();
            long gabOfTime = (currentTime - lastTime);
   
            if (gabOfTime > 150) {
                lastTime = currentTime;
   
                x = event.values[SensorManager.DATA_X];
                y = event.values[SensorManager.DATA_Y];
                z = event.values[SensorManager.DATA_Z];
   
                speed = Math.abs(x + y + z - lastX - lastY - lastZ) /
                        gabOfTime * 10000;
   
                if ((speed > SHAKE_THRESHOLD) && isPressedShake) {
                	vibe.vibrate(80);
                	
                	pd = ProgressDialog.show(this, "Refreshing...", "Foodit is searching other restaurants");
                	pd.setCancelable(false);
                	
                	Timer t = new Timer();
                	t.schedule(new TimerTask() {
						
						@Override
						public void run() {
							pd.dismiss();
							startActivity(new Intent("com.sec.foodit.HomeScreen2Activity"));
		                	overridePendingTransition(0, 0);
						}
					}, 3000);
                	
                }
                lastX = event.values[DATA_X];
                lastY = event.values[DATA_Y];
                lastZ = event.values[DATA_Z];
            }
        }
	}
	

}
